import Vue from 'vue'
import Vuex from 'vuex'
import { currentUserApi } from '@/api/UseApi'
import { currentUserMenu } from '@/api/MenuApi'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  state() {
    return {
      user: {},
      menus:[]
    }
  },
  getters: {
    tree(state){
      return loadTree()
      function loadTree(){
        const tree = state.menus.filter(menu => menu.parentId == 0)
        tree.forEach(item => {
          item.children = getTree(item.id)
        });
        return tree;
      }
      function getTree(id){
        const tree = state.menus.filter(menu => menu.parentId == id)
        tree.forEach(item => {
          item.children = getTree(item.id)
        });
        return tree;
      }
    }
  },
  mutations: {
    setCurrentUser(state, { user }) {
      state.user = user
    },
    setCurrentUserMenu(state, {menus}) {
      state.menus = menus
    }
  },
  actions: {
     loadCurrentUserAction({ commit }) {
      return new Promise( async (resolve, reject) => {
       try {
         const res =await currentUserApi()
         if (res.status === 200) {
          
          
          commit('setCurrentUser', { user: res.data })
          resolve()
         }else{
          reject(res.data)
         }
       } catch (error) {
        reject(error)
       }

      })
    },
    loadCurrentUserMenusAction({commit},{userId}) {
      return new Promise(async(resolve, rejected) => {
        try{
          const res = await currentUserMenu(userId)
          if(res.status == 200){
            const menus = res.data
            commit('setCurrentUserMenu', {menus})
            resolve()
          }else{
            rejected(res)
          }
        }catch(error){
          rejected(error)
        }
      })
    }
    
  },
  plugins: [createPersistedState(
    {
      storage: window.localStorage,
        reducer(state){
          return JSON.parse(JSON.stringify(state))
        }
    }
  )]
})
